package upnp.toy;

import java.util.Dictionary;
import java.util.HashSet;
import java.util.Properties;
import java.util.Random;

import org.apache.felix.upnp.extra.util.UPnPEventNotifier;
import org.osgi.framework.BundleContext;
import org.osgi.service.upnp.UPnPDevice;
import org.osgi.service.upnp.UPnPIcon;
import org.osgi.service.upnp.UPnPService;

public class ToyDevice implements UPnPDevice{

	
	final private String DEVICE_ID = "uuid:Felix-Toy";//+Integer.toHexString(new Random(System.currentTimeMillis()).nextInt());
	
	private BundleContext context;
	private ToyService toyService;
	
	private UPnPService[] services;
	private Dictionary dictionary;
	public static UPnPEventNotifier notifier = null;
	
	
	public ToyDevice(BundleContext context) {
		
		this.context=context;
		toyService=new ToyService();
		services = new UPnPService[]{toyService};
		initDeviceProperties();	
		notifier = new UPnPEventNotifier(context,this,toyService);
		
	}

	
	
	private void initDeviceProperties() {
		
		dictionary=new Properties();
		dictionary.put(UPnPDevice.UPNP_EXPORT, "");
		dictionary.put(
		        org.osgi.service.device.Constants.DEVICE_CATEGORY,
	        	new String[]{UPnPDevice.DEVICE_CATEGORY}
	    );
		dictionary.put(UPnPDevice.FRIENDLY_NAME,"Felix OSGi-UPnP Toy");
		dictionary.put(UPnPDevice.MANUFACTURER,"AGH");
		dictionary.put(UPnPDevice.MANUFACTURER_URL,"http://agh.edu.pl/pp/uhd");
		dictionary.put(UPnPDevice.MODEL_DESCRIPTION,"Upnp Toy to test upnp module of Apache Felix");
		dictionary.put(UPnPDevice.MODEL_NAME,"Simple Toy");
		dictionary.put(UPnPDevice.MODEL_NUMBER,"1.0");
		dictionary.put(UPnPDevice.MODEL_URL,"http://agh.edu.pl/pp/uhd/upnptoy.html");
		dictionary.put(UPnPDevice.SERIAL_NUMBER,"123456789");
		dictionary.put(UPnPDevice.TYPE,"urn:schemas-upnp-org:device:toy:1");
		dictionary.put(UPnPDevice.UDN,DEVICE_ID);
		dictionary.put(UPnPDevice.UPC,"1213456789");
	//embedding - uncomment the line below to enable embedding device
		//dictionary.put(UPnPDevice.CHILDREN_UDN,new String[]{"uuid:Felix-TV"});
		//set also PARENT_UDN property in embedded device!
		
		
		HashSet types = new HashSet(services.length+5);
		String[] ids = new String[services.length];
		for (int i = 0; i < services.length; i++) {
			ids[i]=services[i].getId();
			types.add(services[i].getType());
		}
		
		dictionary.put(UPnPService.TYPE, types.toArray(new String[]{}));
		dictionary.put(UPnPService.ID, ids);
		
		
		
	}



	
	public Dictionary getDescriptions(String arg0) {
		return dictionary;
	}

	
	public UPnPIcon[] getIcons(String arg0) {
		UPnPIcon icon = new ToyIcon();
		return new UPnPIcon[]{icon} ;
	}

	
	public UPnPService getService(String serviceId) {
		if  (serviceId.equals(toyService.getId())) return toyService;
		return null;
	}

	
	public UPnPService[] getServices() {
		return services;
	}

}
